package com.hdax.gulimall.ware.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hdax.common.to.mq.StockDetailTo;
import com.hdax.common.to.mq.StockLockTo;
import com.hdax.common.utils.R;
import com.hdax.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.hdax.gulimall.ware.entity.WareOrderTaskEntity;
import com.hdax.gulimall.ware.exception.NoStockExeption;
import com.hdax.gulimall.ware.feign.OrderFeignService;
import com.hdax.gulimall.ware.feign.ProductFeignService;
import com.hdax.gulimall.ware.service.WareOrderTaskDetailService;
import com.hdax.gulimall.ware.service.WareOrderTaskService;
import com.hdax.gulimall.ware.vo.OrderItemVo;
import com.hdax.gulimall.ware.vo.OrderTo;
import com.hdax.gulimall.ware.vo.SkuHasStockVo;
import com.hdax.gulimall.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdax.common.utils.PageUtils;
import com.hdax.common.utils.Query;

import com.hdax.gulimall.ware.dao.WareSkuDao;
import com.hdax.gulimall.ware.entity.WareSkuEntity;
import com.hdax.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {


    @Autowired
    private WareSkuDao wareSkuDao;


    @Autowired
    private ProductFeignService productFeignService;


    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Autowired
    private WareOrderTaskService wareOrderTaskService;


    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    private OrderFeignService orderFeignService;

    @Autowired
    private ObjectMapper objectMapper;





    /**
     * 解锁库存
     * @param skuId
     * @param wareId
     * @param num
     * @param taskDetailId
     */
    private void unLockStock(Long skuId,Long wareId,Integer num,Long taskDetailId){
        /**
         * 解锁
         */
       wareSkuDao.unLockStock(skuId,wareId,num,taskDetailId);
        /**
         * 修改状态(更新工作单)
         */
       WareOrderTaskDetailEntity wareOrderTaskDetailEntity=new WareOrderTaskDetailEntity();
       wareOrderTaskDetailEntity.setId(taskDetailId);
       wareOrderTaskDetailEntity.setLockStatus(2);
       boolean b = wareOrderTaskDetailService.updateById(wareOrderTaskDetailEntity);
    }




    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        /**
         * skuId:2
         * wareId:2
         */
        QueryWrapper<WareSkuEntity> wareSkuEntityQueryWrapper = new QueryWrapper<>();
        String skuId= (String) params.get("skuId");
        if(!StringUtils.isEmpty(skuId)){
            wareSkuEntityQueryWrapper.eq("sku_id",skuId);
        }
        String wareId= (String) params.get("wareId");
        if(!StringUtils.isEmpty(wareId)){
            wareSkuEntityQueryWrapper.eq("ware_id",wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wareSkuEntityQueryWrapper
        );

        return new PageUtils(page);
    }



    /**
     * 采购完成之后，更新采购单的信息
     * @param skuId
     * @param wareId
     * @param skuNum
     */
    @Override
    public void andStock(Long skuId, Long wareId, Integer skuNum) {
        //判断如果还有当前库存那么就是新增操作
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if(wareSkuEntities==null||wareSkuEntities.size()==0){
            //添加库存商品
            WareSkuEntity wareSkuEntity=new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            R info = productFeignService.info(skuId);
//           try {
               Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");
               wareSkuEntity.setSkuName((String) data.get("skuName"));
            //远程调用
            wareSkuDao.insert(wareSkuEntity);
        }else{
            //修改库存
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }
    }

    /**
     * 判断sku是否有库存
     * @param skuIds
     * @return
     */
    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(item -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            Long count=baseMapper.getSkuStock(item);
            skuHasStockVo.setSkuId(item);
            skuHasStockVo.setHasStock(count==null?false:count>0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return collect;
    }



    /**
     * 解锁库存(解锁订单取消的库存)
     */
    @Override
    public void handleStockLockRelease(StockLockTo stockLockTo) throws JsonProcessingException {
        //库存工作单的详情
        StockDetailTo detailTo = stockLockTo.getDetailTo();
        //数据库查一下关于这个订单的锁库存消息
        WareOrderTaskDetailEntity wareOrderDetail = wareOrderTaskDetailService.getById(detailTo.getId());
        if(wareOrderDetail!=null){
            //解锁
            //订单的id
            //通过工作单详情的id查询工作单的id
            WareOrderTaskEntity wareOrderTask = wareOrderTaskService.getById(stockLockTo.getId());
            String orderSn = wareOrderTask.getOrderSn();
            R orderStatus = orderFeignService.getOrderStatus(orderSn);
            Integer code= (Integer) orderStatus.get("code");
            if(code==0){
                Object data = orderStatus.get("data");
                OrderTo orderTo = objectMapper.readValue(objectMapper.writeValueAsString(data), OrderTo.class);
                if(orderTo!=null&&orderTo.getStatus()==4){
                    //已锁定状态，等待解锁
                    if(wareOrderDetail.getLockStatus()==1){
                        unLockStock(wareOrderDetail.getSkuId(),wareOrderDetail.getWareId(),wareOrderDetail.getSkuNum(),wareOrderDetail.getId());
                    }
                }else if(orderTo!=null&&orderTo.getStatus()==1){
                    /**
                     * 已付款扣库存
                     */
                    //已锁定状态，等待解锁
                    if(wareOrderDetail.getLockStatus()==1){
                        unLockStock(wareOrderDetail.getSkuId(),wareOrderDetail.getWareId(),wareOrderDetail.getSkuNum(),wareOrderDetail.getId());
                    }
                    wareSkuDao.JinWare(wareOrderDetail.getSkuId(),wareOrderDetail.getWareId(),wareOrderDetail.getSkuNum());
                }
            }
        }
    }


    /**
     * 订单取消,解锁库存
     * @param orderTo
     */
    @Override
    @Transactional
    public void handleStockLockRelease(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        WareOrderTaskEntity wareOrderTaskEntity=wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = wareOrderTaskEntity.getId();
        List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", id)
                .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity wareOrderTaskDetailEntity : list) {
            unLockStock(wareOrderTaskDetailEntity.getSkuId(),wareOrderTaskDetailEntity.getWareId(),wareOrderTaskDetailEntity.getSkuNum(),wareOrderTaskEntity.getId());
        }

    }


    /**
     * 库存的锁定
     *
     *
     * 库存的解锁
     *  1、下单成功，订单过期没有支付被系统自动取消，用户手动取消，都要去对库存的解锁
     *  2、下单成功，库存锁定成功，接下来的的业务调用失败，导致订单回滚
     *      之前锁定的库存就要自动解锁
     * @param wareSkuLockVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = NoStockExeption.class)
    public boolean orderLockStock(WareSkuLockVo wareSkuLockVo) {

        /**
         * 保存库存工作单
         */
        WareOrderTaskEntity wareOrderTaskEntity=new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(wareSkuLockVo.getOrderSn());
        wareOrderTaskEntity.setCreateTime(new Date());
        wareOrderTaskService.save(wareOrderTaskEntity);

        //需要锁定的商品
        List<OrderItemVo> locks = wareSkuLockVo.getLocks();
        /**
         * sku
         * count
         * wareids
         */
        List<SkuWareHashStock> collect = locks.stream().map(skuItems -> {
            SkuWareHashStock skuWareHashStock = new SkuWareHashStock();
            Long skuId = skuItems.getSkuId();
            skuWareHashStock.setNum(skuItems.getCount());
            skuWareHashStock.setSkuId(skuId);
            //获取有当前sku的仓库的id(库存-锁定的库存大于0)代表这个仓库有商品
            List<Long> wareIds=wareSkuDao.ListWareIdHasSkuStock(skuId);
            skuWareHashStock.setWareId(wareIds);
            return skuWareHashStock;
        }).collect(Collectors.toList());

        /**
         * 锁sku
         */
        for (SkuWareHashStock skuWareHashStock : collect) {
            //默认没锁
            boolean skuStock=false;
            Long skuId = skuWareHashStock.getSkuId();
            List<Long> wareIds = skuWareHashStock.getWareId();
            if(wareIds==null){
                //抛出异常当前sku没有库存
                throw new NoStockExeption(skuId);
            }
            for (Long wareId : wareIds) {
                //锁定库存(循环仓库，如果一个仓库锁定了sku那么直接break,其他仓库无需锁定)
                Integer count = wareSkuDao.lockSkuStock(skuId, wareId, skuWareHashStock.getNum());
                if(count==1){
                    skuStock=true;
                    /**
                     * 创建工作单详情
                     */
                    WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
                    wareOrderTaskDetailEntity.setSkuId(skuId);
                    wareOrderTaskDetailEntity.setSkuNum(skuWareHashStock.getNum());
                    wareOrderTaskDetailEntity.setWareId(wareId);
                    wareOrderTaskDetailEntity.setTaskId(wareOrderTaskEntity.getId());
                    //已锁定状态
                    wareOrderTaskDetailEntity.setLockStatus(1);
                    //添加库存详情
                    wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);
                    StockLockTo stockLock = new StockLockTo();
                    stockLock.setId(wareOrderTaskEntity.getId());
                    StockDetailTo stockDetailTo=new StockDetailTo();
                    BeanUtils.copyProperties(wareOrderTaskDetailEntity,stockDetailTo);
                    stockLock.setDetailTo(stockDetailTo);
                    //向mq发送消息 工作单的id，商品的数据
                    //TODO 告诉mq库存锁定成功
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",stockLock);
                    break;
                }
            }
            if(skuStock==false){
                //没有锁定成功，抛出异常，可能购买的数量不够
                throw new NoStockExeption(skuId);
            }
        }
        return true;
    }




    @Data
    class SkuWareHashStock {
         private Long skuId;
        /**
         * 库存
         */
        private List<Long> wareId;
        /**
         * 锁定的数量
         */
         private Integer num;
    }
}